//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 李旭阳 on 15/11/9.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    //MARK: 初始化一个webView
    let webView = UIWebView()
    
    //MARK: 在控制器没有创建出来的时候去加载webView
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
    //MARK: ViewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        //加载网页
        loadOauthPage()
    }
    
    //MARK: 让 加载圈消失
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //MARK: 给Model 出来的控制器添加一个关闭Item
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
    //MARK: 实现自动填充 需要在网站上利用开发工具来记录一个string
    @objc private func fullAccount(){
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '1074947943@qq.com' , document.getElementById('passwd').value = 'wan962464123';")
    }
    
    //MARK:监听关闭item 的点击事件
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: 加载网页
    private func loadOauthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
//        let request = NSURLRequest(NSURL(string: urlString))
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL:url!)
        
        webView.loadRequest(request)
    }
}


extension OAuthViewController: UIWebViewDelegate{
    //MARK: 处理webView 的协议方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //MARK: 截取code
    //如果返回 bool  一般表示 如果为true  表示当前对象可以正常 工作  否则就不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //.absoluteString 表示当前的绝对路径
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri){
            return false
        }
        
        guard let query = request.URL?.query else{
            return false
        }
        
        let codeStr = "code="
        //截取字符串 .endIndex 截取到最后
        let code = query.substringFromIndex(codeStr.endIndex)
        print(code)
        print(query)
        
        UserAccountViewModel().loadAccessToKen(code) { (error) -> () in
            
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        
        return false
    }
    
}